package org.example.internet;

import lombok.extern.log4j.Log4j2;
import org.example.param.Config;

import javax.swing.*;
import java.io.*;
import java.net.Socket;
import java.util.Properties;

@Log4j2
public class MessageSender extends Thread{


    private final BufferedReader in;
    private final PrintWriter out;
    private JTextArea chatArea;
    private Socket sendSocket;
    private boolean loop = true;


    public MessageSender(JTextArea chatArea) {
        this.chatArea = chatArea;

        Properties config = Config.getConfig();
        String host = (String) config.get("host");
//        Integer port = (Integer) config.get("port");
        int port = Integer.parseInt((String) config.get("port"));
        try {
            sendSocket = new Socket(host,port);
            in = new BufferedReader(new InputStreamReader(sendSocket.getInputStream()));
            out = new PrintWriter(sendSocket.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }



    }


    public void sendMessage(String meg){

        out.println(meg);
        out.flush();
        if ("exit".equals(meg)){
            //关闭读取
            loop = false;
            log.info("客户端不再读取服务器返回数据");
        }


    }

    @Override
    public void run() {
        try {
            log.info("会话线程启动，等待监听服务器回话");
            while (loop){
                String msg = in.readLine();
                if (msg == null){
                    continue;
                }
                chatArea.append(msg + "\n");
                log.info( "服务器端返回数据" + msg);
            }
        } catch (IOException e) {
            log.error("捕获异常");
        } finally {
            try {
                this.sendMessage("exit");
                loop = false;

                in.close();
                out.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }



    }
}
